<template>
  <div>
    <a-card>
      <a-form :form="form">
        <a-row>
          <a-col :md="20" :sm="24">
            <a-col :md="12" :sm="24">
              <a-form-item
                label="导师编号"
                :labelCol="{span: 7,offset: 1}"
                :wrapperCol="{span: 15, offset: 1}"
              >
                <a-input  v-decorator="['dsbh',
                  {
                    rules: [{ required: true, message: '请选择教职工!' }],
                  }]" disabled/>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="姓名"
                :labelCol="{span: 7,offset: 1}"
                :wrapperCol="{span: 15, offset: 1}"
              >
                <a-input v-decorator="['xm',
                  {
                    rules: [{ required: true, message: '请输入导师姓名!' }],
                  }]" disabled/>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="性别"
                :labelCol="{span: 7,offset: 1}"
                :wrapperCol="{span: 15, offset: 1}"
              >
                <a-select allowClear v-decorator="['xbm',
                  {
                    rules: [{ required: true, message: '请选择性别!' }],
                  }]" >
                  <a-select-option v-for="i in TYPE0011" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            
            <a-col :md="12" :sm="24">
              <a-form-item
                label="身份证"
                :labelCol="{span: 7,offset: 1}"
                :wrapperCol="{span: 15, offset: 1}"
              >
                <a-input @change="zjhmChange" v-decorator="['sfzjh',
                  {
                    rules: [{ required: true, message: '请输入正确的身份证', pattern: /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/}],
                  }]"/>
              </a-form-item>
            </a-col>
            <!-- <a-col :md="12" :sm="24">
              <a-form-item
                label="年龄"
                :labelCol="{span: 7,offset: 1}"
                :wrapperCol="{span: 15, offset: 1}"
              >
                <a-input v-decorator="['nl',
                  {
                    rules: [{ required: true, message: '请输入年龄' }],
                  }]"/>
              </a-form-item>
            </a-col> -->
            <a-col :md="12" :sm="24">
              <a-form-item
                label="出生日期"
                :labelCol="{span: 7,offset: 1}"
                :wrapperCol="{span: 15, offset: 1}"
              >
                <a-date-picker v-decorator="['csrq',
                  {
                    rules: [{ required: true, message: '请选择出生日期!' }],
                  }]" style="width: 100%" format="YYYY-MM-DD"/>
              </a-form-item>
            </a-col>
            
            <a-col :md="12" :sm="24">
              <a-form-item
                label="院系"
                :labelCol="{span: 7,offset: 1}"
                :wrapperCol="{span: 15, offset: 1}"
              >
                <a-select v-decorator="['dwh',
                  {
                    rules: [{ required: true, message: '请选择院系' }],
                  }]" showSearch :filterOption="filterOption" @change="yxChange">
                  <a-select-option v-for="i in selectMenu.yx" :key="i.id" :value="i.dwh">{{ i.dwh }} {{ i.dwmc }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="专业"
                :labelCol="{span: 7,offset: 1}"
                :wrapperCol="{span: 15, offset: 1}"
              >
                <a-select v-decorator="['zyh',
                  {
                    rules: [{ required: true, message: '请选择专业' }],
                  }]" showSearch :filterOption="filterOption">
                  <a-select-option v-for="i in selectMenu.zy" :key="i.id" :value="i.zyh">{{ i.zyh }} {{ i.zymc }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="职称"
                :labelCol="{span: 7,offset: 1}"
                :wrapperCol="{span: 15, offset: 1}"
              >
                <a-select v-decorator="['zc',
                  {
                    rules: [{ required: true, message: '请选择职称' }],
                  }]">
                  <a-select-option v-for="i in HWXNYJYZC" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="电子邮箱"
                :labelCol="{span: 7,offset: 1}"
                :wrapperCol="{span: 15, offset: 1}"
              >
                <a-input v-decorator="['dzxx',
                  {
                    rules: [{ required: true, message: '请输入电子信箱',pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/ }],
                  }]"/>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="手机号码"
                :labelCol="{span: 7,offset: 1}"
                :wrapperCol="{span: 15, offset: 1}"
              >
                <a-input v-decorator="['lxdh',
                  {
                    rules: [{ required: true, message: '请输入正确的手机号码',pattern: /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/ }],
                  }]"/>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="固定电话"
                :labelCol="{span: 7,offset: 1}"
                :wrapperCol="{span: 15, offset: 1}"
              >
                <a-input :maxLength="maxLength" v-decorator="['zzdh',{
                    rules: [{ required: true, message: '请输入不超过4位的区号数字和不超过8位的座机电话',pattern: /0\d{2,3}-\d{7,8}/}],
                  }]" @change="onChange"/>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="研究方向"
                :labelCol="{span: 7,offset: 1}"
                :wrapperCol="{span: 15, offset: 1}"
              >
                <a-input v-decorator="['yjfx',
                  {
                    rules: [{ required: true, message: '请输入研究方向' }],
                  }]"/>
              </a-form-item>
            </a-col>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-item
              label=""
              :labelCol="{span: 0,offset: 1}"
              :wrapperCol="{span: 20, offset: 1}"
              selfUpdate
            >
              <a-upload
                name="avatar"
                style="width:120px;height:120px;"
                listType="picture-card"
                class="avatar-uploader"
                :showUploadList="false"
                :action="uploadUrl"
                list-type="picture"
                :headers="{
                  Authorization: $store.state.account.token
                }"
                @change="handleChange"
              >
                <img v-if="imageUrl" :src="imageUrl" style="width: 200px;height: 200px;" alt="avatar" />
                <div v-else>
                  <a-icon :type="loading ? 'loading' : 'plus'" />
                  <div class="ant-upload-text">上传照片</div>
                </div>
              </a-upload>
              <a-input v-decorator="['zpdz']" type="hidden"/>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <div class="ant-pro-footer-toolbar">
      <a-button style="float: right;margin-top: 10px;" @click="creatTeacher" :loading="loadingBtn" type="primary">保存</a-button>
      <a-button style="float: right;margin-top: 10px;margin-right: 20px;" @click="$router.back()">返回</a-button>
    </div>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import moment from 'moment'

const selectArr = ['TYPE0320', 'TYPE0321', 'TYPE0011', 'HWXNYJYZC', 'TYPE0018', 'TYPE0023']
function getBase64 (img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}
export default {
  data () {
    return {
      selectMenu: {},
      teacherInfo: {},
      loading: false,
      uploadUrl:`${process.env.SERVICE_URL}upload/img`,
      imageUrl: '',
      loadingBtn: false,
      id:this.$db.get('USER').gh,
      maxLength: 12,
    }
  },
  beforeCreate () {
    this.form = this.$form.createForm(this)
  },
  computed: {
    ...mapState({
      TYPE0321: state => state.app['TYPE0321'], // 是否在岗
      TYPE0011: state => state.app['TYPE0011'], // 性别
      TYPE0320: state => state.app['TYPE0320'], // 导师状态
      HWXNYJYZC: state => state.app['HWXNYJYZC'], // 职称
      TYPE0018: state => state.app['TYPE0018'], // 学历
      TYPE0023: state => state.app['TYPE0023'] // 学位
    })
  },
  created () {
    selectArr.forEach(v => {
      this.$store.dispatch('app/setDictionary', v)
    })
    this.initSelectMenu()
    this.$nextTick(() => {
      this.$api.overseas.teacherInfo(this.id).then(res => {
        this.teacherInfo = res.data
        if (res.data.rdpzny) {
          res.data.rdpzny = res.data.rdpzny.slice(0,4) + '-' + res.data.rdpzny.slice(4,6) + '-' + '01'
        }
        if (res.data.scrbdny) {
          res.data.scrbdny = res.data.scrbdny.slice(0,4) + '-' + res.data.scrbdny.slice(4,6) + '-' + '01'
        }
        if (res.data.scrsdny) {
          res.data.scrsdny = res.data.scrsdny.slice(0,4) + '-' + res.data.scrsdny.slice(4,6) + '-' + '01'
        }
        if (res.data.zpdz) {
          this.imageUrl = `${process.env.IMG_URL}${res.data.zpdz}`
        }
        if (res.data.byxxszsf) {
          this.handlePChange(res.data.byxxszsf)
        }
        this.id = res.data.id
        this.$changeDate(res.data)
        this.form.setFieldsValue({...res.data, dsbh: res.data.gh})
        this.yxChange(res.data.dwh)
      })
    })
  },
  methods: {
    initSelectMenu () {
      let allRequest = [
        this.$api.base.collegeAll(),
        this.$api.base.areaList()
      ]
      Promise.all(allRequest).then(res => {
        this.selectMenu = {
          yx: res[0].data,
          province: res[1].data
        }
      })
    },
    filterOption (value, op) {
      return op.componentOptions.children[0].text.indexOf(value) !== -1
    },
    yxChange (code) {
      // this.$set(this.queryParam, 'zy', '')
      if (code) {
        this.$api.base.majorAll({lsdwh: code}).then(res => {
          this.$set(this.selectMenu, 'zy', res.data)
        })
      } else {
        this.$set(this.selectMenu, 'zy', [])
      }
    },
    handleChange (info) {
      if (info.file.status === 'uploading') {
        this.loading = true
        return
      }
      if (info.file.status === 'done') {
        let path = info.file.response.data[0]
        this.form.setFieldsValue({zpdz: path})
        this.imageUrl = `${process.env.IMG_URL}${path}`
      }
    },
    beforeUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      if (!isJPG) {
        this.$message.error('You can only upload JPG file!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!')
      }
      return isJPG && isLt2M
    },
    setData (option, key) {
      this.form.setFieldsValue({[key]: option.data.attrs.name})
    },
    handlePChange(v) {
      this.form.setFieldsValue({byxxdm: ''})
      this.$api.base.schoolInfoQueryAll({xzqhsdm: v}).then(res => {
        this.$set(this.selectMenu, 'schoolList' , res.data)
      })
    },
    creatTeacher () {
      this.form.validateFields((err, values) => {
        if (err) {
          return
        }
        try {
          this.loadingBtn = true
          for (const key in values) {
            if (['rdpzny', 'scrbdny', 'scrsdny'].includes(key) && values[key]) {
              values[key] = values[key].format('YYYYMM')
            }
          }
          this.$DateToString(values)
          values.id = this.id
          values.gh = values.dsbh
          this.$message.loading('保存中', 0)
          this.$api.overseas.teacherUpdate(values).then(res => {
            this.$message.success(res.msg, 4)
          }).finally(() => {
            setTimeout(() => {
              this.$message.destroy()
            }, 4000);
            this.loadingBtn = false
            // this.form.resetFields()
          })
        } catch (error) {
          console.log(error)
        }
      })
    },
    onChange(e){
      
    },
    zjhmChange(v){
      // let sfzjlxm = this.form.getFieldValue('sfzjh');
      const {value} = v.target;
      if(value && (value.length === 15 || value.length === 18)){//居民省份证
        this.form.setFieldsValue({"csrq":moment(this.getBirthdatByIdNo(value), 'YYYY-MM-DD')});
        // this.form.setFieldsValue({"nl": });
        console.log(this.form.getFieldsValue().csrq)
        // this.getAgeFromBirthday(this.form.getFieldsValue().csrq)
      }
    },
    //获取出生日期
    getBirthdatByIdNo (IdNO){
      let birthday = "";
      if (IdNO.length==18) {
        birthday = IdNO.substr(6,8);
        return birthday.replace(/(.{4})(.{2})/,"$1-$2-");
      }else if(IdNO.length==15){
        birthday = "19"+IdNO.substr(6,6);
        return birthday.replace(/(.{4})(.{2})/,"$1-$2-");
      }else{
        return ""; 
      }
    },
    //获取年龄
    // getAgeFromBirthday(birthday) {
    //   let birthDate = new Date(birthday)
    //   console.log(birthDate)
    //   let nowDateTime = new Date()
    //   let age = nowDateTime.getFullYear() - birthDate.getFullYear()
    //   if (nowDateTime.getMonth() < birthDate.getMonth() ||
    //     (nowDateTime.getMonth() == birthDate.getMonth() &&
    //       nowDateTime.getDate() < birthDate.getDate())) {
    //     age--
    //   }
    //   this.form.setFieldsValue({"nl": age});
    //   // return age
    // }
  }
}
</script>
